<template>
  <div class="network-test">
    <div class="test-header">
      <h2>网络连接诊断工具</h2>
      <p>用于诊断和解决网络连接问题</p>
    </div>

    <div class="test-section">
      <h3>基本信息</h3>
      <div class="info-grid">
        <div class="info-item">
          <span class="label">网络状态:</span>
          <span :class="['status', networkStatus ? 'online' : 'offline']">
            {{ networkStatus ? '在线' : '离线' }}
          </span>
        </div>
        <div class="info-item">
          <span class="label">后端地址:</span>
          <span class="value">http://localhost:34405</span>
        </div>
        <div class="info-item">
          <span class="label">超时设置:</span>
          <span class="value">15秒</span>
        </div>
      </div>
    </div>

    <div class="test-section">
      <h3>连接测试</h3>
      <div class="test-buttons">
        <el-button type="primary" @click="testBackend" :loading="testing">
          测试后端连接
        </el-button>
        <el-button type="success" @click="testCaptcha" :loading="testing">
          测试验证码API
        </el-button>
        <el-button type="warning" @click="testLogin" :loading="testing">
          测试登录API
        </el-button>
        <el-button type="info" @click="runFullDiagnosis" :loading="testing">
          完整诊断
        </el-button>
      </div>
    </div>

    <div class="test-section">
      <h3>测试结果</h3>
      <div class="test-results">
        <div v-for="result in testResults" :key="result.id" 
             :class="['result-item', result.status]">
          <div class="result-header">
            <span class="result-name">{{ result.name }}</span>
            <span class="result-status">{{ result.statusText }}</span>
            <span class="result-time">{{ result.time }}ms</span>
          </div>
          <div v-if="result.error" class="result-error">
            {{ result.error }}
          </div>
        </div>
      </div>
    </div>

    <div class="test-section">
      <h3>解决方案</h3>
      <div class="solutions">
        <div class="solution-item">
          <h4>1. 检查后端服务</h4>
          <p>确保后端服务正在运行在 http://localhost:34405</p>
        </div>
        <div class="solution-item">
          <h4>2. 检查防火墙</h4>
          <p>确保防火墙允许访问端口 34405</p>
        </div>
        <div class="solution-item">
          <h4>3. 检查CORS设置</h4>
          <p>确保后端允许来自前端的跨域请求</p>
        </div>
        <div class="solution-item">
          <h4>4. 重启服务</h4>
          <p>尝试重启前端和后端服务</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElButton } from 'element-plus'
import { apiWreit } from '@/Ulter/AxiosHepler'

const networkStatus = ref(navigator.onLine)
const testing = ref(false)
const testResults = ref<any[]>([])

// 监听网络状态
const handleOnline = () => {
  networkStatus.value = true
  ElMessage.success('网络已连接')
}

const handleOffline = () => {
  networkStatus.value = false
  ElMessage.error('网络已断开')
}

onMounted(() => {
  window.addEventListener('online', handleOnline)
  window.addEventListener('offline', handleOffline)
})

onUnmounted(() => {
  window.removeEventListener('online', handleOnline)
  window.removeEventListener('offline', handleOffline)
})

// 添加测试结果
const addTestResult = (name: string, status: 'success' | 'error' | 'warning', statusText: string, time: number, error?: string) => {
  testResults.value.unshift({
    id: Date.now(),
    name,
    status,
    statusText,
    time,
    error
  })
}

// 测试后端连接
const testBackend = async () => {
  testing.value = true
  const startTime = Date.now()
  
  try {
    const response = await fetch('http://localhost:34405', {
      method: 'GET',
      mode: 'no-cors'
    })
    
    const time = Date.now() - startTime
    addTestResult('后端连接', 'success', '连接成功', time)
    ElMessage.success('后端连接正常')
  } catch (error: any) {
    const time = Date.now() - startTime
    addTestResult('后端连接', 'error', '连接失败', time, error.message)
    ElMessage.error('后端连接失败: ' + error.message)
  } finally {
    testing.value = false
  }
}

// 测试验证码API
const testCaptcha = async () => {
  testing.value = true
  const startTime = Date.now()
  
  try {
    await apiWreit.get('/api/Mange/GetCaptcha/captcha')
    const time = Date.now() - startTime
    addTestResult('验证码API', 'success', '请求成功', time)
    ElMessage.success('验证码API正常')
  } catch (error: any) {
    const time = Date.now() - startTime
    const errorMsg = error.response?.data?.message || error.message || '未知错误'
    addTestResult('验证码API', 'error', '请求失败', time, errorMsg)
    ElMessage.error('验证码API失败: ' + errorMsg)
  } finally {
    testing.value = false
  }
}

// 测试登录API
const testLogin = async () => {
  testing.value = true
  const startTime = Date.now()
  
  try {
    // 发送一个测试请求（不包含实际登录数据）
    await apiWreit.post('/api/Mange/LoginUser', {
      username: 'test',
      password: 'test'
    })
    const time = Date.now() - startTime
    addTestResult('登录API', 'success', '接口可访问', time)
    ElMessage.success('登录API接口可访问')
  } catch (error: any) {
    const time = Date.now() - startTime
    if (error.response && error.response.status !== 500) {
      // 如果不是服务器错误，说明接口是可访问的
      addTestResult('登录API', 'success', '接口可访问', time)
      ElMessage.success('登录API接口可访问')
    } else {
      const errorMsg = error.response?.data?.message || error.message || '未知错误'
      addTestResult('登录API', 'error', '请求失败', time, errorMsg)
      ElMessage.error('登录API失败: ' + errorMsg)
    }
  } finally {
    testing.value = false
  }
}

// 完整诊断
const runFullDiagnosis = async () => {
  testing.value = true
  testResults.value = []
  
  ElMessage.info('开始完整网络诊断...')
  
  await testBackend()
  await new Promise(resolve => setTimeout(resolve, 500))
  
  await testCaptcha()
  await new Promise(resolve => setTimeout(resolve, 500))
  
  await testLogin()
  
  ElMessage.success('网络诊断完成')
  testing.value = false
}
</script>

<style scoped>
.network-test {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.test-header {
  text-align: center;
  margin-bottom: 30px;
}

.test-header h2 {
  color: #409eff;
  margin-bottom: 10px;
}

.test-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.test-section h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.label {
  font-weight: 600;
  color: #666;
}

.status.online {
  color: #67c23a;
  font-weight: 600;
}

.status.offline {
  color: #f56c6c;
  font-weight: 600;
}

.value {
  color: #333;
  font-family: monospace;
}

.test-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.test-results {
  max-height: 400px;
  overflow-y: auto;
}

.result-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 4px;
  border-left: 4px solid;
}

.result-item.success {
  background: #f0f9ff;
  border-left-color: #67c23a;
}

.result-item.error {
  background: #fef0f0;
  border-left-color: #f56c6c;
}

.result-item.warning {
  background: #fdf6ec;
  border-left-color: #e6a23c;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.result-error {
  margin-top: 8px;
  color: #f56c6c;
  font-size: 12px;
  font-family: monospace;
}

.solutions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.solution-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.solution-item h4 {
  margin: 0 0 8px 0;
  color: #409eff;
}

.solution-item p {
  margin: 0;
  color: #666;
  font-size: 14px;
}
</style>
